package com.smart.home.multi;

import com.smart.home.netty.handler.AbstractChannelInboundHandler;
import com.smart.home.util.CommandDecoder;
import com.smart.home.util.CommandEncoder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;

/**
 * 客户端2处理
 *
 * @author zhangpeng
 * @version 1.0
 * @date 2017-03-22
 */
public class Client2Handler extends AbstractChannelInboundHandler {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String content = "91231265CC00000001";
        byte[] decode = CommandEncoder.decode(content);
        ctx.writeAndFlush(Unpooled.copiedBuffer(decode));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        String result = ByteBufUtil.hexDump(msg);
        System.out.println(result);
        String[] msgs = result.split("eeeeeeeeeeee");
        for (String mg : msgs) {
            System.out.println("接收信息："+CommandDecoder.hexToStringGBK(mg)+"   ");
        }
        //System.out.println("==="+CommandDecoder.hexToStringGBK(result));
        //byte[] b = new byte[msg.readableBytes()];
        //msg.readBytes(b);
        //String s = CommandDecoder.hexToString(b);
        //System.out.println("【客户端】client1接收信息：" + result+"===="+ s);
       /* String result = ByteBufUtil.hexDump(msg);
        System.out.println("hex:"+result);*/
        /*System.out.println("客户端2接收信息："+msg.toString(CharsetUtil.UTF_8));*/
        System.out.println("----------------------------------------------------------");
       // ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("客户端client1出现异常");
        cause.printStackTrace();
        ctx.close();
    }
}
